package top.yjp.jtf.plugin;

import com.alibaba.excel.EasyExcel;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.vfs.VirtualFile;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class ExcelEditor extends AnAction {
    public ExcelEditor() {
        // 动态设置插件的右键菜单文本,原因是plugins.xml无法使用动态的文本
        super(MessageBundle.message("plugin.action.text"));
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取选中的文件
        VirtualFile[] files = e.getData(com.intellij.openapi.actionSystem.CommonDataKeys.VIRTUAL_FILE_ARRAY);

        if (files != null && files.length > 0) {
            for (VirtualFile file : files) {
                if (file.getName().endsWith(".xlsx")) {
                    openExcelFile(file,e);
                    break;
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "请选择一个 Excel 文件！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void openExcelFile(VirtualFile virtualFile,AnActionEvent e) {
//        File file = new File(virtualFile.getPath());
//
//        // 读取 Excel 数据
//        List<Map<Integer, String>> data = EasyExcel.read(file).excelType(ExcelTypeEnum.XLSX).sheet().doReadSync();
//
//        if (data.isEmpty()) {
//            JOptionPane.showMessageDialog(null, "Excel 文件没有数据！", "错误", JOptionPane.ERROR_MESSAGE);
//            return;
//        }
        FileEditorManager.getInstance(Objects.requireNonNull(e.getProject())).openFile(virtualFile,true);
    }


    private void saveExcelFile(File file, JTable table) {
        // 获取表格数据
        int rowCount = table.getRowCount();
        int columnCount = table.getColumnCount();
        List<List<String>> data = new ArrayList<>();

        for (int i = 0; i < rowCount; i++) {
            List<String> row = new ArrayList<>();
            for (int j = 0; j < columnCount; j++) {
                row.add((String) table.getValueAt(i, j));
            }
            data.add(row);
        }

        // 写入 Excel
        EasyExcel.write(file).head(List.class).sheet("Sheet1").doWrite(data);
        JOptionPane.showMessageDialog(null, "文件已保存！", "保存成功", JOptionPane.INFORMATION_MESSAGE);
    }
}
